iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
自我挑戰組

leetcode題目分享系列 第 17

[Day 17] 847. Shortest Path Visiting All Nodes

  • 分享至 

  • xImage
  •  
class Solution {
    struct State {
     int mask, node, dist;
    };
public:
    int shortestPathLength(vector<vector<int>>& graph) {
        int n = graph.size();
        int all_visited = (1 << n) - 1;
        queue<State> q;
        unordered_set<int> visited;
        
        for (int i = 0; i < n; ++i) {
            q.push({1 << i, i, 0});
            visited.insert((1 << i) * 16 + i);
        }
        
        while (!q.empty()) {
            State cur = q.front(); q.pop();
            
            if (cur.mask == all_visited) {
                return cur.dist;
            }
            
            for (int neighbor : graph[cur.node]) {
                int new_mask = cur.mask | (1 << neighbor);
                int hash_value = new_mask * 16 + neighbor;
                
                if (visited.find(hash_value) == visited.end()) {
                    visited.insert(hash_value);
                    q.push({new_mask, neighbor, cur.dist + 1});
                }
            }
        }
        
        return -1;
    }
};

上一篇
[Day 16] 1631. Path With Minimum Effort
下一篇
[Day 18] 1337. The K Weakest Rows in a Matrix
系列文
leetcode題目分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言